package util;

import java.util.List;
import java.util.Map;

import javax.naming.InitialContext;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import dao.ClientDAO;
import entity.Client;

/**
 * 
 * Primefaces datatable DataModel implementation for server-side pagination 
 *
 */

public class ClientLazyList extends LazyDataModel<Client> {

	private String searchString;
	private List<Client> resultList;
	ClientDAO clientDAO;

	@Override
	public List<Client> load(int startAt, int resultsPerPage, String sortField,
			SortOrder sortOrder, Map<String, String> filters) {
		if (clientDAO == null) {
			try {
				InitialContext ctx = new InitialContext();
				clientDAO = (ClientDAO) ctx.lookup("java:global/PaidClinic/JPAClientDAO!dao.ClientDAO");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
		resultList = clientDAO.selectClientsByNameOrLastnamePartPaged(
				searchString, startAt, resultsPerPage);
		int resultCount = clientDAO.selectClientCountByNameOrLastnamePart(searchString);
		this.setRowCount(resultCount);
		return resultList;
	}

	@Override
	public Client getRowData(String rowKey) {
		Integer id = Integer.valueOf(rowKey);
		for (Client client : resultList) {
			if (id.equals(client.getId())) {
				return client;
			}
		}
		return null;
	}

	@Override
	public Integer getRowKey(Client client) {
		return client.getId();
	}

	public void setSearchString(String searchString) {
		this.searchString = searchString;
	}

}
